package com.innovation.chengzhangriji.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.support.v4.widget.ExtraSwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.ExtraRecyclerView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Discover;
import com.innovation.chengzhangriji.DiscoverSaveComment;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.DiscoverChangeResponse;
import com.innovation.chengzhangriji.http.DiscoverCommentResponse;
import com.innovation.chengzhangriji.http.DiscoverContentResponse;
import com.innovation.chengzhangriji.http.DiscoverLikeResponse;
import com.innovation.chengzhangriji.http.DiscoverResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.event.BaseEvent;
import com.innovation.chengzhangriji.ui.model.DiscoverModel;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.DiscoverAdapter;
import com.innovation.chengzhangriji.ui.widget.FriendItemDecoration;
import com.innovation.chengzhangriji.util.ChZhRJUtils;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.orhanobut.logger.Logger;

import org.apache.http.Header;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

public class DiscoverActivity extends BaseActivity implements ExtraSwipeRefreshLayout.OnRefreshListener, DiscoverAdapter.Observer, DiscoverAdapter.TextObserver, DiscoverAdapter.PhotoObserver, DiscoverAdapter.AudioObserver, DiscoverAdapter.VideoObserver, DiscoverAdapter.LikeObserver, DiscoverAdapter.CommentObserver, DiscoverAdapter.MilestoneObserver, View.OnClickListener, CuteToolbar.OnClickCuteToolbarListener, ExtraRecyclerView.OnLoadMoreListener, DiscoverAdapter.OnClickErrorListener, View.OnTouchListener {

    // 修改为一次加载 10条
    private static final int SIZE = 10;

    private ExtraSwipeRefreshLayout swipe;

    private ExtraRecyclerView recyclerView;

    private DiscoverAdapter adapter;

    private RelativeLayout layout;

    private EditText editComment;

    private ArrayList<DiscoverModel> list;

    private long syncTime = 0;

    private long loadTime;

    private int positionComment = -1;

    private int positionLayerComment = -1;

    private String targetUuid;

    private String targetName;

    private String targetNickname;

    private String targetUserId;

    private int positionAudio = -1;

    private MediaPlayer player;

//    private NewCommentBroadcastReceiver newCommentBroadcastReceiver;

    private ImageView pointImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        if(getIntent().getBooleanExtra("newComment", false)) {
//            Intent intent = new Intent(this, DiscoverCommentActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//            startActivity(intent);
//        }

        // 修改线程策略，让主线程能访问网络
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        setContentView(R.layout.activity_discover);
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        toolbar.setOnClickCuteToolbarListener(this);
        swipe = (ExtraSwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swipe.setOnRefreshListener(this);
        recyclerView = (ExtraRecyclerView) findViewById(R.id.recycler);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        adapter = new DiscoverAdapter(this);
        adapter.setObserver(this);
        adapter.setTextObserver(this);
        adapter.setPhotoObserver(this);
        adapter.setAudioObserver(this);
        adapter.setVideoObserver(this);
        adapter.setMilestoneObserver(this);
        adapter.setLikeObserver(this);
        adapter.setCommentObserver(this);
        adapter.setOnClickErrorListener(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new FriendItemDecoration());
        recyclerView.setItemAnimator(null);
        recyclerView.setLoadMoreCount(0);
        recyclerView.setOnLoadMoreListener(this);
        recyclerView.setOnTouchListener(this);

        layout = (RelativeLayout) findViewById(R.id.layout_bottom);
        editComment = (EditText) findViewById(R.id.edit_comment);
        ImageView buttonComment = (ImageView) findViewById(R.id.button_comment);
        buttonComment.setOnClickListener(this);

        // 新消息的小红点
        pointImage = (ImageView) findViewById(R.id.image_point_msg);

        list = new ArrayList<DiscoverModel>();
        // changeLikeList = new ArrayList<DiscoverLikeResponse>();
        // changeCommentList = new ArrayList<DiscoverCommentResponse>();

        // 先加载本地日记数据
        list.addAll(DatabaseManager.getInstance(DiscoverActivity.this).getLocalDiscover());
        adapter.notifyDataSetChanged();

        // 刷新网络数据
        swipe.post(new Runnable() {
            @Override
            public void run() {
                swipe.setRefreshing(true);
            }
        });

        // 注册新广播，用于接收新评论信息
        // registerNewCommentReceiver();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK) {
            if(data.getBooleanExtra("needRefresh", false)) {
                // 刷新页面
                swipe.post(new Runnable() {
                    @Override
                    public void run() {
                        swipe.setRefreshing(true);
                    }
                });
            }
        }
    }

    // 注册新广播
//    private void registerNewCommentReceiver() {
//        IntentFilter intentFilter = new IntentFilter(Config.ACTION_NEW_COMMENT_DOWNLOAD_SUCCEED);
//        newCommentBroadcastReceiver = new NewCommentBroadcastReceiver();
//        LocalBroadcastManager.getInstance(this).registerReceiver(newCommentBroadcastReceiver, intentFilter);
//    }
//
//    // 取消注册新广播
//    private void unregisterNewCommentReceiver() {
//        newCommentBroadcastReceiver = new NewCommentBroadcastReceiver();
//        LocalBroadcastManager.getInstance(this).unregisterReceiver(newCommentBroadcastReceiver);
//    }

    // 请求网络接口，清理未读消息数量
    private void clearUnReadMsgCount() {
        Client.requestAllPushRead(this, mLoginInfo.getPhone(), mLoginInfo.getToken().getAccessToken(), new ResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
            }

            @Override
            public void onInnovationFailure(String msg) {
                super.onInnovationFailure(msg);
            }
        }, new Client.NetworkUnavailableListener() {

            @Override
            public void networkUnavailable() {

            }
        });
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            // 隐藏输入法
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(recyclerView.getWindowToken(), 0);
            layout.setVisibility(View.INVISIBLE);
        }
        return false;
    }

    // 接收新评论
//    private class NewCommentBroadcastReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            // 当接收到新通知广播后，显示小红点
//            pointImage.setVisibility(View.VISIBLE);
//        }
//    }


    @Override
    public void onEvent(BaseEvent event) {
        super.onEvent(event);
        if(event.getType() == BaseEvent.TYPE_NEW_COMMENT_DOWNLOAD_SUCCESS) {
            // 当接收到新通知广播后，显示小红点
            pointImage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 判断是否有新评论，有就显示小红点
        if(Config.getHasNewComment(this)) {
            pointImage.setVisibility(View.VISIBLE);
        } else {
            pointImage.setVisibility(View.INVISIBLE);
        }
        // 清除未读数量
//        ShortcutBadger.removeCount(this);
        clearUnReadMsgCount();
        // 清除新日记标记
        Config.setHasNewMessage(this, false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (positionAudio != -1) {
            list.get(positionAudio).getContent().setIsAudioPlay(false);
            adapter.notifyItemChanged(positionAudio);
            positionAudio = -1;
            stopPlayback();
        }
    }

    @Override
    protected void receiveChZhRJMessage(int type, int tag) {
//        if (tag != 1) { // 2 新评论 3 赞 4 评论回复
//            Config.startLocalCommentService(this);
//        }
    }

    @Override
    public void onClickLeft() {
//        if (!getIntent().getBooleanExtra(Config.EXTRA_CAN_BACK, true)) {
//            Intent intent = new Intent(this, HomeActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//            startActivity(intent);
//            finish();
//        } else {
            finish();
//        }
    }

    @Override
    public void onBackPressed() {
        onClickLeft();
    }

    @Override
    public void onClickRight() {
        Intent intent = new Intent(this, DiscoverCommentActivity.class);
        startActivityForResult(intent, 0);
    }

    @Override
    public void onRefresh() {
        requestDiscover();
    }

    @Override
    public void onLoadMore() {
        if (!adapter.isEnd()) {
            requestLoadMoreDiscover(loadTime);
        }
    }

    @Override
    public void onClickError() {
        adapter.setError(false);
        adapter.notifyItemChanged(length());
        requestLoadMoreDiscover(loadTime);
    }

    @Override
    public int length() {
        if (list == null) {
            return 0;
        }
        return list.size();
    }

    @Override
    public int type(int position) {
        if (list.get(position).getContent().getType() == 1) {
            if (TextUtils.isEmpty(list.get(position).getContent().getMilestone())) {
                return 0;
            } else {
                return 4;
            }
        }
        return list.get(position).getContent().getType() - 1;
    }

    @Override
    public String userName(int position) {
        return list.get(position).getContent().getName();
    }

    @Override
    public String userUrl(int position) {
        return list.get(position).getContent().getHeadUrl();
    }

    @Override
    public String babyName(int position) {
        String babyName = list.get(position).getContent().getBabyName();
        if(TextUtils.isEmpty(babyName)) {
            Baby baby = DatabaseManager.getInstance(this).queryBaby(list.get(position).getContent().getBabyId());
            if(baby != null) {
                babyName = baby.getName();
            } else {
                babyName = "未知";
            }
        }
        return "来自" + " " + ChZhRJUtils.getText(list.get(position).getContent().getDiaryName(), babyName + "的成长日记");
    }

    @Override
    public String babyUrl(int position) {
        return list.get(position).getContent().getBabyHeadUrl();
    }

    @Override
    public int babySex(int position) {
        Baby baby = DatabaseManager.getInstance(this).queryBaby(list.get(position).getContent().getBabyId());
        if(baby != null) {
            return baby.getGender();
        } else {
            return 3;
        }
    }

    @Override
    public String time(int position) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.SIMPLIFIED_CHINESE);
        Date date = new Date(list.get(position).getContent().getCreateTS());
        return sf.format(date);
    }

    @Override
    public boolean showBottom(int position) {
        return showLike(position) || showComment(position);
    }

    @Override
    public String text(int position) {
        return list.get(position).getContent().getText();
    }

    @Override
    public void onClickPhoto(int position1, int position2) {
        Intent intent = new Intent(this, DiscoverGalleryActivity.class);
        intent.putExtra("photoUrls", list.get(position1).getContent().getPhotos());
        intent.putExtra("index", position2);
        startActivity(intent);
    }

    @Override
    public String photoLabel(int position) {
        return list.get(position).getContent().getTheme();
    }

    @Override
    public String photoContent(int position) {
        return list.get(position).getContent().getText();
    }

    @Override
    public String[] photoUrl(int position) {
        return list.get(position).getContent().getPhotos();
    }

    @Override
    public void onClickAudio(int position) {
        if (positionAudio == position) {
            positionAudio = -1;
            list.get(position).getContent().setIsAudioPlay(false);
            adapter.notifyItemChanged(position);
            // 停止播放
            stopPlayback();
        } else {
            if (positionAudio != -1) {
                list.get(positionAudio).getContent().setIsAudioPlay(false);
                adapter.notifyItemChanged(positionAudio);
                // 停止播放
                stopPlayback();
            }
            positionAudio = position;
            list.get(position).getContent().setIsAudioPlay(true);
            adapter.notifyItemChanged(position);
            // 开始播放
            playAudio(list.get(position).getContent().getAudioLocalUrl());
        }
    }

    @Override
    public int audioLength(int position) {
        return list.get(position).getContent().getMediaLength();
    }

    @Override
    public boolean audioPlay(int position) {
        return list.get(position).getContent().isAudioPlay();
    }

    @Override
    public boolean audioShow(int position) {
        return list.get(position).getContent().isAudioShow();
    }

    @Override
    public boolean audioDownloading(int position) {
        return list.get(position).getContent().isAudioDownloading();
    }

    @Override
    public boolean audioDownloadSucceed(int position) {
        return list.get(position).getContent().isAudioDownloadSucceed();
    }

    @Override
    public void downloadAudio(final int position) {
        // 网络请求下载音频
        String audioUrl = list.get(position).getContent().getAudio();
        int start = audioUrl.indexOf(Config.AUDIO);
        String subUrl = audioUrl.substring(start);
        File file = new File(getExternalCacheDir(), String.valueOf(subUrl.hashCode()));
        if (file.exists()) {
            list.get(position).getContent().setIsAudioDownloadSucceed(true);
            list.get(position).getContent().setIsAudioShow(true);
            list.get(position).getContent().setAudioLocalUrl(file.getPath());
            final Handler handler = new Handler();
            final Runnable r = new Runnable() {
                public void run() {
                    adapter.notifyItemChanged(position);
                }
            };
            handler.post(r);
        } else {
            list.get(position).getContent().setIsAudioDownloading(true);
            Client.downloadFile(this, audioUrl, new FileAsyncHttpResponseHandler(file) {
                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                    list.get(position).getContent().setIsAudioDownloading(false);
                    adapter.notifyItemChanged(position);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, File file) {
                    list.get(position).getContent().setIsAudioDownloading(false);
                    adapter.notifyItemChanged(position);
                }
            }, new Client.NetworkUnavailableListener() {
                @Override
                public void networkUnavailable() {
                    list.get(position).getContent().setIsAudioDownloading(false);
                    adapter.notifyItemChanged(position);
                }
            });
        }
    }

    @Override
    public void onClickVideo(int position) {
        Intent intent = new Intent(this, DiscoverVideoActivity.class);
        intent.putExtra("videoUrl", list.get(position).getContent().getVideo());
        startActivity(intent);
    }

    @Override
    public String thumbnailUrl(int position) {
        return list.get(position).getContent().getScreenshot();
    }

    @Override
    public String milestone(int position) {
        return list.get(position).getContent().getMilestone();
    }

    @Override
    public void onClickLike(int position) {
        requestLike(position);
    }

    @Override
    public boolean isLike(int position) {
        if (list.get(position).getLike() == null || list.get(position).getLike().size() == 0) {
            return false;
        }
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return false;
        }
        String userId = loginInfo.getUserID();
        for (int i = 0; i < list.get(position).getLike().size(); i++) {
            if (userId.equals(list.get(position).getLike().get(i).getLikeId())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int likeNumber(int position) {
        if (list.get(position).getLike() == null || list.get(position).getLike().size() == 0) {
            return 0;
        }
        return list.get(position).getLike().size();
    }

    @Override
    public boolean showLike(int position) {
        return likeNumber(position) > 0;
    }

    @Override
    public ArrayList<String> likeList(int position) {
        if (list.get(position).getLike() == null || list.get(position).getLike().size() == 0) {
            return null;
        }
        ArrayList<String> stringArrayList = new ArrayList<String>();
        for (int i = 0; i < list.get(position).getLike().size(); i++) {
            stringArrayList.add(list.get(position).getLike().get(i).getLikeName());
        }
        return stringArrayList;
    }

    @Override
    public void onClickComment(int position) {
        positionComment = position;
        positionLayerComment = -1;
        targetUuid = "";
        targetName = "";
        targetNickname = "";
        layout.setVisibility(View.VISIBLE);
        editComment.requestFocus();
        editComment.setHint(null);
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    @Override
    public void onClickComment(int position1, int position2) {
        positionComment = position1;
        positionLayerComment = position2;

        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return;
        }
        String userId = loginInfo.getUserID();
        int num = 0;
        for (int i = 0; i < list.get(position1).getComment().size(); i++) {
            if (positionLayerComment == num) {
                if (userId.equals(list.get(position1).getComment().get(i).getCommentId())) {
                    deleteDialog(list.get(position1).getComment().get(i));
                    return;
                } else {
                    targetUuid = list.get(position1).getComment().get(i).getId();
                    targetName = list.get(position1).getComment().get(i).getCommentName();
                    targetNickname = list.get(position1).getComment().get(i).getCommentNickname();
                    targetUserId = list.get(position1).getComment().get(i).getCommentId();
                    break;
                }
            }
            num++;
        }
        layout.setVisibility(View.VISIBLE);
        editComment.requestFocus();
        editComment.setHint("回复" + targetName);
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    @Override
    public int commentNumber(int position) {
        if (list.get(position).getComment() == null || list.get(position).getComment().size() == 0) {
            return 0;
        }
        return list.get(position).getComment().size();
    }

    @Override
    public boolean showComment(int position) {
        return commentNumber(position) > 0;
    }

    @Override
    public ArrayList<DiscoverAdapter.CommentModel> commentList(int position) {
        if (list.get(position).getComment() == null || list.get(position).getComment().size() == 0) {
            return null;
        }
        ArrayList<DiscoverAdapter.CommentModel> commentArrayList = new ArrayList<DiscoverAdapter.CommentModel>();
        for (int i = 0; i < list.get(position).getComment().size(); i++) {

            DiscoverAdapter.CommentModel model = new DiscoverAdapter.CommentModel();
            model.setUserName1(list.get(position).getComment().get(i).getCommentName());
            model.setUserName2(list.get(position).getComment().get(i).getTargetName());
            model.setContent(list.get(position).getComment().get(i).getComment());
            commentArrayList.add(model);
        }
        return commentArrayList;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_comment:
                requestComment();
                break;
        }
    }

    private void requestDiscover() {
        stopPlayback();
        mLoginInfo = Config.getLoginInfo(this);
        if (mLoginInfo == null) {
            return;
        }
        String phone = mLoginInfo.getPhone();
        String token = mLoginInfo.getToken().getAccessToken();
        final int length = SIZE;
        Client.requestDiscover(this, phone, token, syncTime, length, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                Logger.json(value.toString());
                DiscoverChangeResponse responses = get(value.toString(), DiscoverChangeResponse.class);
                if (responses == null || responses.getContent() == null || responses.getContent().length == 0) {
                    tipShow("没有新消息了");
                    return;
                }
                if (responses.getContent().length < SIZE) {
                    adapter.setEnd(true);
                } else {
                    adapter.setEnd(false);
                }
                list.clear();
                int discoverLength = responses.getContent().length;
                int likeLength = responses.getLike().length;
                int commentLength = responses.getComment().length;
                loadTime = responses.getContent()[discoverLength - 1].getCreateTS();
                DiscoverModel[] discovers = new DiscoverModel[discoverLength];
                for (int i = 0; i < discoverLength; i++) {
                    // 日记
                    discovers[i] = new DiscoverModel();
                    discovers[i].setContent(responses.getContent()[i]);
                    // 赞
                    ArrayList<DiscoverLikeResponse> tempLikeList = new ArrayList<DiscoverLikeResponse>();
                    for (int j = 0; j < likeLength; j++) {
                        if (responses.getLike()[j].getLikeState() == 0) continue;
                        if (discovers[i].getContent().getDiaryId().equals(responses.getLike()[j].getDiaryId())) {
                            tempLikeList.add(responses.getLike()[j]);
                        }
                    }
                    Collections.sort(tempLikeList, new Comparator<DiscoverLikeResponse>() {
                        @Override
                        public int compare(DiscoverLikeResponse lhs, DiscoverLikeResponse rhs) {
                            if (lhs.getTs() < rhs.getTs()) {
                                return -1;
                            }
                            return 0;
                        }
                    });
                    discovers[i].setLike(tempLikeList);
                    // 评论
                    ArrayList<DiscoverCommentResponse> tempCommentList = new ArrayList<DiscoverCommentResponse>();
                    for (int j = 0; j < commentLength; j++) {
                        if (responses.getComment()[j].getCommentState() == 0) continue;
                        if (discovers[i].getContent().getDiaryId().equals(responses.getComment()[j].getDiaryId())) {
                            tempCommentList.add(responses.getComment()[j]);
                        }
                    }
                    Collections.sort(tempCommentList, new Comparator<DiscoverCommentResponse>() {
                        @Override
                        public int compare(DiscoverCommentResponse lhs, DiscoverCommentResponse rhs) {
                            if (lhs.getTs() < rhs.getTs()) {
                                return -1;
                            }
                            return 0;
                        }
                    });
                    discovers[i].setComment(tempCommentList);
                    list.add(discovers[i]);
                }
                // 保存到本地，类型2
                saveDiscoverToLocal(list);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onInnovationFinish() {
                swipe.setRefreshing(false);
            }

            @Override
            public void onInnovationExceptionFinish() {
                swipe.setRefreshing(false);
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                swipe.setRefreshing(false);
                if (list.size() == 0) {
                    // 从本地获取日记数据
                    list.addAll(DatabaseManager.getInstance(DiscoverActivity.this).getLocalDiscover());
                    adapter.notifyDataSetChanged();
                }
                tipShow("网络连接失败");
            }
        });
    }

    // 日记圈的日记保存到本地
    private void saveDiscoverToLocal(List<DiscoverModel> models) {
        // 评论 和 赞
        ArrayList<DiscoverSaveComment> comments = new ArrayList<>();
        DatabaseManager.getInstance(this).deleteRjqDiscover();
        for(DiscoverModel model : models) {
            Discover discover = setupDiscover(model.getContent());
            // 照片
            DatabaseManager.getInstance(this).insertOrReplaceDiscover(discover, model.getContent().getPhotos());
            // 评论
            DiscoverCommentResponse[] commentResponses = new DiscoverCommentResponse[model.getComment().size()];
            commentResponses = model.getComment().toArray(commentResponses);
            addComment(commentResponses, comments, 2, null);
            // 赞
            DiscoverLikeResponse[] likeResponses = new DiscoverLikeResponse[model.getLike().size()];
            likeResponses = model.getLike().toArray(likeResponses);
            addComment(likeResponses, comments, 2, null);
        }
        // 保存评论到本地数据库
        DatabaseManager.getInstance(this).insertOrReplaceDiscoverSaveCommentInTx(comments);
    }

    // 创建 日记 对象
    private Discover setupDiscover(DiscoverContentResponse response) {
        Discover discover = new Discover();
        discover.setDiaryID(response.getDiaryId());
        discover.setIsDelete(response.getState() == 0);
        discover.setAudio(response.getAudio());
        discover.setUserHeadUrl(response.getHeadUrl());
        discover.setBabyID(response.getBabyId());
        discover.setBabyName(response.getBabyName());
        discover.setCreateTS(response.getCreateTS());
        discover.setDuration(response.getMediaLength());
        discover.setGrowthStageID(response.getState());
        discover.setMemberName(response.getName());
        discover.setMilestone(response.getMilestone());
        discover.setScreenshot(response.getScreenshot());
        discover.setText(response.getText());
        discover.setTheme(response.getTheme());
        discover.setNickName(response.getNickName());
        discover.setType(response.getType());
        // 接口没返回 UserId，不在更新 UserID
        discover.setUserID(response.getUserId());
        discover.setDiaryFrom(2); // 来自日记圈
        discover.setVideo(response.getVideo());
        discover.setBabyHeadUrl(response.getBabyHeadUrl());
        return discover;
    }

    // 添加普通评论
    private void addComment(DiscoverCommentResponse[] responses, ArrayList<DiscoverSaveComment> comments, int from, String userId) {
        if(responses == null || responses.length == 0) return;
        for(int i = 0; i < responses.length; i++) {
            if(responses[i].getCommentState() == 0) {
                // 删除本地评论
                DatabaseManager.getInstance(this.getApplicationContext()).deleteComment(responses[i].getId());
                return;
            }
            DiscoverSaveComment comment = new DiscoverSaveComment();
            comment.setCommentType(1);
            comment.setContent(responses[i].getComment());
            comment.setCreateTS(responses[i].getTs());
            comment.setDiaryID(responses[i].getDiaryId());
            comment.setOperationState(responses[i].getCommentState());
            comment.setUserID(responses[i].getCommentId());
            comment.setReplyUserID(responses[i].getTargetUserId());
            comment.setReplyNickname(responses[i].getTargetNickname());
            comment.setUserNickname(responses[i].getCommentNickname());
            comment.setReplyIdentity(responses[i].getTargetId());
            comment.setUserHeadUrl(responses[i].getCommentHeadUrl());
            comment.setIsNew(true);
            comment.setMemberName(responses[i].getCommentName());
            comment.setReplyMemberName(responses[i].getTargetName());
            comment.setIsLocal(false);
            if(from == 1) {
                // 只有当为最新评论时，才记录所属用户的信息
                comment.setBelongUserId(userId);
            }
            comment.setIdentity(responses[i].getId());
            comment.setFrom(from); // 1：最新评论 2：日记本身评论
            comments.add(comment);
        }
    }

    // 添加点赞评论
    private void addComment(DiscoverLikeResponse[] responses, ArrayList<DiscoverSaveComment> comments, int from, String userId) {
        if(responses == null || responses.length == 0) return;
        for(int i = 0; i < responses.length; i++) {
            if(responses[i].getLikeState() == 0) {
                DatabaseManager.getInstance(this.getApplicationContext()).deleteComment(responses[i].getId());
                continue;
            }
            DiscoverSaveComment comment = new DiscoverSaveComment();
            comment.setCommentType(2);
            comment.setCreateTS(responses[i].getTs());
            comment.setDiaryID(responses[i].getDiaryId());
            comment.setOperationState(responses[i].getLikeState());
            comment.setUserID(responses[i].getLikeId());
            comment.setUserHeadUrl(responses[i].getLikeHeadUrl());
            comment.setUserNickname(responses[i].getLikeNickname());
            comment.setIsNew(true);
            comment.setMemberName(responses[i].getLikeName());
            comment.setIsLocal(false);
            if(from == 1) {
                // 只有当为最新评论时，才记录所属用户的信息
                comment.setBelongUserId(userId);
            }
            comment.setIdentity(responses[i].getId());
            comment.setFrom(from); // 1：最新评论 2：日记本身评论
            comments.add(comment);
        }
    }

    private void requestLoadMoreDiscover(final long ts) {
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        final int length = SIZE;
        Client.requestLoadDiscover(this, phone, token, ts, length, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                DiscoverResponse[] responses = get(value.toString(), DiscoverResponse[].class);
                if (responses == null || responses.length == 0) { // 没有更早的数据了
                    adapter.setEnd(true);
                    adapter.notifyItemChanged(length());
                } else {
                    int discoverLength = responses.length;
                    DiscoverModel[] discovers = new DiscoverModel[discoverLength];
                    for (int i = 0; i < discoverLength; i++) {
                        // 日记
                        discovers[i] = new DiscoverModel();
                        discovers[i].setContent(responses[i].getContent());
                        // 赞
                        int likeLength = responses[i].getLike().length;
                        ArrayList<DiscoverLikeResponse> tempLikeList = new ArrayList<DiscoverLikeResponse>();
                        tempLikeList.addAll(Arrays.asList(responses[i].getLike()).subList(0, likeLength));
                        Collections.sort(tempLikeList, new Comparator<DiscoverLikeResponse>() {
                            @Override
                            public int compare(DiscoverLikeResponse lhs, DiscoverLikeResponse rhs) {
                                if (lhs.getTs() < rhs.getTs()) {
                                    return -1;
                                }
                                return 0;
                            }
                        });
                        discovers[i].setLike(tempLikeList);
                        // 评论
                        int commentLength = responses[i].getComment().length;
                        ArrayList<DiscoverCommentResponse> tempCommentList = new ArrayList<DiscoverCommentResponse>();
                        tempCommentList.addAll(Arrays.asList(responses[i].getComment()).subList(0, commentLength));
                        Collections.sort(tempCommentList, new Comparator<DiscoverCommentResponse>() {
                            @Override
                            public int compare(DiscoverCommentResponse lhs, DiscoverCommentResponse rhs) {
                                if (lhs.getTs() < rhs.getTs()) {
                                    return -1;
                                }
                                return 0;
                            }
                        });
                        discovers[i].setComment(tempCommentList);
                        list.add(discovers[i]);
                        // 只保存评论到数据库
                        saveCommentToLocal(responses[i].getComment(), responses[i].getLike());
                    }
                    loadTime = responses[responses.length - 1].getContent().getCreateTS();
                    adapter.setEnd(false);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onInnovationFinish() {
                super.onInnovationFinish();
                recyclerView.setLoadMore(false);
            }

            @Override
            public void onInnovationExceptionFinish() {
                super.onInnovationExceptionFinish();
                recyclerView.setLoadMore(false);
            }
        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                recyclerView.setLoadMore(false);
            }
        });
    }

    // 只保存评论到数据库
    private void saveCommentToLocal(DiscoverCommentResponse[] commentResponses, DiscoverLikeResponse[] likeResponses) {
        ArrayList<DiscoverSaveComment> comments = new ArrayList<>();
        addComment(commentResponses, comments, 2, null);
        addComment(likeResponses, comments, 2, null);
        DatabaseManager.getInstance(this).insertOrReplaceDiscoverSaveCommentInTx(comments);
    }

    private void requestLike(final int position) {
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        String userId = loginInfo.getUserID();
        String nickname = loginInfo.getName();
        Baby baby = DatabaseManager.getInstance(this).queryBaby(list.get(position).getContent().getBabyId());
        if (baby == null) {
            tipShow("已取消关注,不可以操作");
            return;
        }
        String name = baby.getParentName();
        final String diaryId = list.get(position).getContent().getDiaryId();

        String uuid = null;
        int likeIndex = -1;
        boolean like = true;
        if (list.get(position).getLike() == null || list.get(position).getLike().size() == 0) {
            uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
        } else {
            for (int i = 0; i < list.get(position).getLike().size(); i++) {
                if (userId.equals(list.get(position).getLike().get(i).getLikeId()) && list.get(position).getLike().get(i).getLikeState() == 1) {
                    uuid = list.get(position).getLike().get(i).getId();
                    likeIndex = i;
                    like = false;
                    break;
                }
            }
            if (like) {
                uuid = UUID.randomUUID().toString();
                uuid = uuid.replaceAll("-", "");
            }
        }

        // ---------- 离线赞部分 Start -------------
        final DiscoverSaveComment comment = new DiscoverSaveComment();
        comment.setCommentType(2);
        comment.setUserHeadUrl(loginInfo.getUrl());
        comment.setIsNew(false);
        comment.setDiaryID(diaryId);
        comment.setIdentity(uuid);
        comment.setUserID(userId);
        comment.setOperationState(1);
        comment.setMemberName(name);
        comment.setUserNickname(nickname);
        comment.setFrom(2);
        comment.setCreateTS(System.currentTimeMillis());
        // ---------- 离线赞部分 End -------------

        if (like) {

            DiscoverLikeResponse response = new DiscoverLikeResponse();
            response.setDiaryId(diaryId);
            response.setId(uuid);
            response.setLikeId(userId);
            response.setLikeState(1);
            response.setLikeName(name);
            response.setLikeNickname(nickname);
            response.setTs(comment.getCreateTS());

            list.get(position).getLike().add(response);
            adapter.notifyItemChanged(position);

            // Client.requestLike(this, phone, token, diaryId, uuid, new ResponseHandler(), networkUnavailableSampleImpl());
            Client.requestLike(this, phone, token, diaryId, uuid, new ResponseHandler() {

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    super.onInnovationSuccess(value);
                    // 有网的时候存储到本地
                    comment.setIsLocal(false);
                    DatabaseManager.getInstance(DiscoverActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(comment);
                }
            }, new Client.NetworkUnavailableListener() {

                @Override
                public void networkUnavailable() {
                    // 离线时，存储离线评论，待有网的时候处理
                    comment.setIsLocal(true);
                    DatabaseManager.getInstance(DiscoverActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(comment);
                }
            });
        } else {

            if (likeIndex != -1) {
                list.get(position).getLike().remove(likeIndex);
                adapter.notifyItemChanged(position);
            }

            // Client.requestUnLike(this, phone, token, diaryId, uuid, new ResponseHandler(), networkUnavailableSampleImpl());
            final String commentId = uuid;
            Client.requestUnLike(this, phone, token, diaryId, uuid, new ResponseHandler() {

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    super.onInnovationSuccess(value);
                    DatabaseManager.getInstance(DiscoverActivity.this.getApplicationContext()).deleteComment(commentId);
                }
            }, new Client.NetworkUnavailableListener() {

                @Override
                public void networkUnavailable() {
                    // 离线时，存储离线评论，待有网的时候处理
                    comment.setOperationState(0);
                    comment.setIsLocal(true);
                    DatabaseManager.getInstance(DiscoverActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(comment);
                }
            });
        }
    }

    private void requestComment() {
        if (TextUtils.isEmpty(editComment.getText())) {
            return;
        }
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        String userId = loginInfo.getUserID();
        Baby baby = DatabaseManager.getInstance(this).queryBaby(list.get(positionComment).getContent().getBabyId());
        if (baby == null) {
            tipShow("已取消关注,不可以操作");
            return;
        }
        String name = baby.getParentName();
        String nickname = loginInfo.getName();
        String diaryId = list.get(positionComment).getContent().getDiaryId();
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        String comment = editComment.getText().toString();

        DiscoverCommentResponse response = new DiscoverCommentResponse();
        response.setDiaryId(diaryId);
        response.setId(uuid);
        response.setCommentId(userId);
        response.setCommentState(1);
        response.setCommentName(name);
        response.setCommentNickname(nickname);
        response.setComment(comment);
        response.setTs(System.currentTimeMillis());

        // -------- 离线评论部分 Start ---------
        final DiscoverSaveComment saveComment = new DiscoverSaveComment();
        saveComment.setCommentType(1);
        saveComment.setDiaryID(diaryId);
        saveComment.setIdentity(uuid);
        saveComment.setUserID(userId);
        saveComment.setOperationState(1);
        saveComment.setMemberName(name);
        saveComment.setUserNickname(nickname);
        saveComment.setContent(comment);
        saveComment.setCreateTS(response.getTs());
        saveComment.setUserHeadUrl(loginInfo.getUrl());
        saveComment.setIsNew(false);
        saveComment.setFrom(2);
        // -------- 离线评论部分 End ---------

        if (positionLayerComment != -1) {
            response.setTargetId(targetUuid);
            response.setTargetName(targetName);
            response.setTargetNickname(targetNickname);

            //---------- 离线评论部分 Start ---------
            saveComment.setReplyIdentity(targetUuid);
            saveComment.setReplyMemberName(targetName);
            saveComment.setReplyNickname(targetNickname);
            saveComment.setReplyUserID(targetUserId);
            // -------- 离线评论部分 End ---------
        }

        list.get(positionComment).getComment().add(response);
        adapter.notifyItemChanged(positionComment);

        layout.setVisibility(View.INVISIBLE);
        editComment.setText(null);
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        // Client.requestComment(this, phone, token, diaryId, uuid, comment, targetUuid, new ResponseHandler(), networkUnavailableSampleImpl());
        Client.requestComment(this, phone, token, diaryId, uuid, comment, targetUuid, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                // 将评论保存到本地
                saveComment.setIsLocal(false);
                DatabaseManager.getInstance(DiscoverActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(saveComment);
            }
        }, new Client.NetworkUnavailableListener() {

            @Override
            public void networkUnavailable() {
                // 离线时，存储离线评论，待有网的时候处理
                saveComment.setIsLocal(true);
                DatabaseManager.getInstance(DiscoverActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(saveComment);
            }
        });
    }

    private void deleteDialog(final DiscoverCommentResponse response) {
        new AlertDialog.Builder(this).setTitle("删除该条评论?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                list.get(positionComment).getComment().remove(response);
                adapter.notifyItemChanged(positionComment);
                // requestDeleteComment(response.getId());
                requestDeleteComment(response);
            }
        }).setNegativeButton("取消", null).show();
    }

    private void requestDeleteComment(final DiscoverCommentResponse comment) {
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return;
        }

        // 离线评论
        final DiscoverSaveComment saveComment = new DiscoverSaveComment();
        saveComment.setCommentType(1);
        saveComment.setDiaryID(comment.getDiaryId());
        saveComment.setIdentity(comment.getId());
        saveComment.setUserID(comment.getCommentId());
        saveComment.setOperationState(0); // 取消赞
        saveComment.setMemberName(comment.getCommentName());
        saveComment.setUserNickname(comment.getCommentNickname());
        saveComment.setContent(comment.getComment());
        saveComment.setCreateTS(comment.getTs());
        saveComment.setUserHeadUrl(loginInfo.getUrl());
        saveComment.setIsNew(false);
        saveComment.setFrom(2);

        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        Client.requestDeleteComment(this, phone, token, saveComment.getIdentity(), new ResponseHandler() {
            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                DatabaseManager.getInstance(DiscoverActivity.this.getApplicationContext()).deleteComment(saveComment.getIdentity());
            }
        }, new Client.NetworkUnavailableListener() {

            @Override
            public void networkUnavailable() {
                saveComment.setOperationState(0);
                saveComment.setIsLocal(true);
                DatabaseManager.getInstance(DiscoverActivity.this.getApplicationContext()).insertOrReplaceDiscoverSaveComment(saveComment);
            }
        });
    }

//    private void requestDeleteComment(String uuid) {
//        LoginInfo loginInfo = Config.getLoginInfo(this);
//        if (loginInfo == null) {
//            return;
//        }
//        String phone = loginInfo.getPhone();
//        String token = loginInfo.getToken().getAccessToken();
//        Client.requestDeleteComment(this, phone, token, uuid, new ResponseHandler(), networkUnavailableSampleImpl());
//    }

    private void playAudio(final String path) {
        player = new MediaPlayer();
        try {
            player.setDataSource(path);
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopPlayback();
                }
            });
            player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    stopPlayback();
                    return true;
                }
            });
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
            stopPlayback();
        }
    }

    private void stopPlayback() {
        if(positionAudio != -1) {
            list.get(positionAudio).getContent().setIsAudioPlay(false);
            adapter.notifyItemChanged(positionAudio);
            positionAudio = -1;
        }
        if (player == null) // we were not in playback
            return;
        player.stop();
        player.release();
        player = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消广播的注册
//        unregisterNewCommentReceiver();
    }
}
